{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from torch.nn import init\n",
    "import numpy as np\n",
    "import sys\n",
    "sys.path.append(\"..\")\n",
    "import d2lzh_pytorch as d21"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size=256\n",
    "train_iter,test_iter=d21.load_data_fashion_mnist(batch_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_inputs=784\n",
    "num_outputs=10\n",
    "class LinearNet(nn.Module):\n",
    "    def __init__(self,num_inputs,num_outputs):\n",
    "        super().__init__()\n",
    "        self.linear=nn.Linear(num_inputs,num_outputs)\n",
    "    def forward(self,x):\n",
    "        y=self.linear(x.view(x.shape[0],-1))\n",
    "        return y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import OrderedDict\n",
    "net=nn.Sequential(OrderedDict([\n",
    "(\"flatten\",d21.FlattenLayer()),\n",
    "(\"linear\",nn.Linear(num_inputs,num_outputs))]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "init.normal(net.linear.weight,mean=0,std=0.01)\n",
    "init.constant_(net.linear.bias,val=0)\n",
    "loss=nn.CrossEntropyLoss()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "epoch 1, loss 0.0031, train acc 0.751, test acc 0.762\nepoch 2, loss 0.0022, train acc 0.812, test acc 0.799\nepoch 3, loss 0.0021, train acc 0.826, test acc 0.817\nepoch 4, loss 0.0020, train acc 0.833, test acc 0.823\nepoch 5, loss 0.0019, train acc 0.838, test acc 0.826\n"
    }
   ],
   "source": [
    "optimizer=torch.optim.SGD(net.parameters(),lr=0.1)\n",
    "num_epoches=5\n",
    "d21.train_ch3(net,train_iter,test_iter,loss,num_epoches,batch_size,None,None,optimizer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python37464bitbasecondab04fb1e447c742be8678bc28fb07e8e2",
   "display_name": "Python 3.7.4 64-bit ('base': conda)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}